/*
 * 创建日期 2010-5-11
 *
 * 成都天和软件公司
 * 电话：028-85425861
 * 传真：028-85425861-8008
 * 邮编：610041 
 * 版权所有
 */
package  org.fantasy.common.compile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;

/**
 *  测试实例
 * @author: 王文成
 * @version: 1.0
 * @since 2010-5-11
 */
public class ComplieTest{
    
    static SqlBuilder builder;
    
    public static void prepare(){
        File file = null;
        String classname = null;
        try {
            String classDir = System.getProperty("user.dir");
            System.out.println("classDir=" + classDir);
            file = File.createTempFile("RunTime", ".java", new File(classDir));
            String filename = file.getName();
            classname = filename.substring(0, filename.lastIndexOf('.'));
            PrintWriter out = new PrintWriter(new FileOutputStream(file));
            // 代码
            StringBuffer code = new StringBuffer();
            code.append("public class " + classname + " implements  org.fantasy.common.compile.SqlBuilder{\n");
            code.append("   public void run() { System.out.println(\"DynamicCompile Success.\"); }\n");
            code.append("   public String getSql(java.util.Map map) { return new StringBuffer(\"我是SQL select * from dual\").toString();}\n");
            code.append("}\n");
            System.out.println(code);
            out.println(code);
            out.flush();
            out.close();
            // 编译
            String[] arg = new String[] { "-d", classDir, filename };
            com.sun.tools.javac.Main.compile(arg);// JAVA_HOME/jdk/lib/tools.jar
            URL url = new URL("file:/" + classDir + File.separator);
            // 动态加载/执行
            URLClassLoader loader = new URLClassLoader(new URL[] { url });
            Class<?> clazz = loader.loadClass(classname);
            Object obj = clazz.newInstance();
            Method method = clazz.getMethod("run");
            method.invoke(obj);
            builder = ((SqlBuilder)obj);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (file != null) {
                file.delete();
                file = new File(classname + ".class");
                if (file != null)
                    file.delete();
            }
        }
    }
    
    public static void use() throws Exception{
        System.out.println( "sql=" + builder.getSql(null));
        System.out.println( "sql=" + builder.getSql(null));
        System.out.println( "sql=" + builder.getSql(null));
    }
    
    public static void main(String[] args)  throws Exception{
        prepare();
        use();
    }
}
